const fs = require('fs'),
      url = require('url'),
      mime = require('mime'),
      http = require('http'),
      zlib = require('zlib'),
      { join } = require('path'),
      { promisify } = require('util');

const stat = promisify(fs.stat);

/*
* 写法一
const server = http.createServer();
server.on('request', (req, res) => {
    res.end('ok');
}) */

/**
 * 写法二
 * Accept-Encoding 支持的的压缩格式
 */
const server = http.createServer(async (req, res) => {
    let { pathname } = url.parse(req.url);
    let filepath = join(__dirname,pathname);

    try{
        // let statObj = await stat(filepath);
        // console.log(statObj);
        // mime可以根据不同文件类型返回不同的Content-type
        res.setHeader('Content-type',mime.getType(pathname));
        let accod = req.headers['accept-encoding'];
        // 内容协商
        if(accod) {
            if(accod.match(/\bgzip\b/)) {
                res.setHeader('Content-Encoding', 'gzip');
                fs.createReadStream(filepath).pipe(zlib.createGzip()).pipe(res);
            }else if(accod.match(/\bdeflate\b/)) {
                res.setHeader('Content-Encoding', 'deflate');
                fs.createReadStream(filepath).pipe(zlib.createDeflate()).pipe(res);
            }else {
                fs.createReadStream(filepath).pipe(res);
            }
        }else {
            fs.createReadStream(filepath).pipe(res);
        }
    }catch(e) {
        res.statusCode = 404;
        res.end();
    }
});

server.listen(8000);
